<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Docker 镜像代理加速</title>
    <link rel="icon" href="https://cdn.jsdelivr.net/gh/dqzboy/Blog-Image/BlogCourse/docker-proxy.png" type="image/png">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        :root {
            --primary-color: #2196F3;
            --secondary-color: #1976D2;
            --background-color: #f8f9fa;
            --container-bg: #ffffff;
            --text-color: #333333;
            --border-color: #e0e0e0;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            background-color: var(--background-color);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background-color: var(--container-bg);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        /* 调整顶部导航样式 */
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0.5rem 1rem;  /* 减小上下内边距 */
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            height: 40px;  /* 稍微减小logo大小 */
            width: auto;
        }

        .nav-menu {
            display: flex;
            gap: 0.8rem;  /* 减小菜单项之间的间距 */
        }

        .nav-menu a {
            color: var(--text-color);
            text-decoration: none;
            padding: 0.35rem 0.8rem;  /* 减小菜单项的内边距 */
            border-radius: 4px;
            transition: all 0.3s ease;
            font-size: 0.95rem;  /* 稍微调整字体大小 */
        }

        .nav-menu a:hover {
            background-color: var(--primary-color);
            color: white;
        }

        .container {
            width: 80%; /* 设置固定比例宽度 */
            min-width: 1000px; /* 设置最小宽度 */
            max-width: 1400px; /* 设置最大宽度 */
            margin: 2rem auto;
            padding: 0;
            flex: 1 0 auto;
            display: flex;
            flex-direction: column;
            min-height: calc(100vh - 180px); /* 减去header和footer的高度 */
        }

        .tab-container {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 0.5rem;
        }

        .tab {
            padding: 0.75rem 1.5rem;
            border: none;
            background: none;
            color: var(--text-color);
            cursor: pointer;
            font-weight: 500;
            position: relative;
        }

        .tab.active {
            color: var(--primary-color);
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -0.5rem;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: var(--primary-color);
        }

        .content {
            display: none;
            background: var(--container-bg);
            padding: 3rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            flex: 1;
            min-height: calc(100vh - 300px); /* 确保最小高度 */
            width: 100%;
            box-sizing: border-box;
        }

        .content.active {
            display: flex;
            flex-direction: column;
        }

        input[type="text"] {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin-bottom: 1rem;
            font-size: 1rem;
        }

        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: var(--secondary-color);
        }

        pre {
            background-color: #f6f8fa;
            padding: 1rem;
            border-radius: 4px;
            overflow-x: auto;
            position: relative;
        }

        .copy-btn {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            background-color: #e9ecef;
            color: var(--text-color);
        }

        .search-result-item {
            margin-bottom: 1rem;
            padding: 1rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
        }

        .official-badge {
            background-color: #28a745;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 3px;
            font-size: 0.75rem;
            margin-left: 0.5rem;
        }

        .footer {
            background-color: var(--container-bg);
            padding: 1.5rem;
            text-align: center;
            border-top: 1px solid var(--border-color);
            margin-top: auto; /* 将 footer 推到底部 */
            flex-shrink: 0; /* 防止 footer 被压缩 */
        }

        /* 返回顶部按钮样式优化 */
        #backToTopBtn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 44px;
            height: 44px;
            background: linear-gradient(145deg, #2196F3, #1976D2);
            color: white;
            border: none;
            border-radius: 12px;
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
            padding: 0;
            font-size: 24px;
            line-height: 1;
        }

        #backToTopBtn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 16px rgba(33, 150, 243, 0.4);
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                align-items: flex-start;
            }

            .nav-menu {
                margin-top: 1rem;
                flex-direction: column;
                width: 100%;
            }

            .tab-container {
                flex-wrap: wrap;
            }

            .container {
                padding: 1rem;
                min-height: calc(100vh - 140px);
            }
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; }
            15% { opacity: 1; }
            85% { opacity: 1; }
            100% { opacity: 0; }
        }

        /* 搜索结果容器样式 */
        #searchResults {
            flex: 1;
            overflow-y: auto;
            margin-top: 1rem;
        }

        /* 文档内容容器样式 */
        #documentationContent {
            display: none;
        }

        #documentationContent.active {
            display: grid;
            grid-template-columns: 250px 1fr;
            gap: 2rem;
        }

        #documentList {
            border-right: 1px solid var(--border-color);
            padding-right: 1rem;
        }

        #documentationText {
            flex: 1;
            overflow-y: auto;
        }

        /* 镜像加速内容样式 */
        #accelerateContent .input-group {
            margin-bottom: 2rem;
        }

        #result {
            flex: 1;
        }

        #commandsContainer {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .step {
            background: #fff;
            padding: 1.5rem;
            border-radius: 6px;
            border: 1px solid var(--border-color);
            margin-bottom: 1rem;
        }

        .step h3 {
            color: var(--primary-color);
            margin-top: 0;
            margin-bottom: 1rem;
            font-size: 1.1rem;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.5rem;
        }

        .step pre {
            background: #1e1e1e;
            color: #fff;
            padding: 1rem;
            border-radius: 4px;
            margin: 0;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
            font-size: 0.9rem;
        }

        .step pre code {
            color: #fff;
        }

        .copy-btn {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            padding: 0.35rem 0.75rem;
            font-size: 0.8rem;
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .copy-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        /* 适配移动端 */
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
                min-height: calc(100vh - 140px);
            }

            #documentationContent.active {
                grid-template-columns: 1fr;
            }

            #documentList {
                border-right: none;
                border-bottom: 1px solid var(--border-color);
                padding-bottom: 1rem;
                margin-bottom: 1rem;
            }
        }

        /* 适配移动端 */
        @media (max-width: 1024px) {
            .container {
                width: 95%;
                min-width: auto;
                padding: 0 1rem;
            }

            .content {
                padding: 1.5rem;
            }
        }

        .quick-guide {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin: 2rem 0;
            border: 1px solid var(--border-color);
        }

        .popular-images {
            margin-top: 2rem;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }

        .image-card {
            background: #fff;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 1rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .image-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .image-card h3 {
            margin: 0 0 0.5rem 0;
            color: var(--primary-color);
        }

        .image-card .description {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 1rem;
        }

        .command-terminal {
            background: #2D2D2D;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 1rem;
        }

        .terminal-header {
            background: #404040;
            padding: 8px 15px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .terminal-button {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .button-red {
            background: #FF5F56;
        }

        .button-yellow {
            background: #FFBD2E;
        }

        .button-green {
            background: #27C93F;
        }

        .step {
            margin-bottom: 1rem;
        }

        .step h3 {
            color: var(--primary-color);
            margin: 0 0 0.5rem 0;
            font-size: 1rem;
            font-weight: 500;
        }

        .step pre {
            background: #2D2D2D;
            margin: 0;
            padding: 0;
        }

        .step pre code {
            display: block;
            padding: 12px 15px;
            color: #fff;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 0.9rem;
            line-height: 1.4;
        }

        .copy-btn {
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            padding: 4px 8px;
            font-size: 0.8rem;
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
            border: none;
            border-radius: 4px;
            opacity: 0;
            transition: opacity 0.2s;
        }

        .step pre:hover .copy-btn {
            opacity: 1;
        }

        .command-terminal pre {
            margin: 0;
            padding: 8px 0;  /* 增加上下内边距 */
            background: transparent;
            position: relative;
            display: flex;
            align-items: center;
        }

        .command-terminal pre code {
            display: block;
            padding: 12px 15px;  /* 增加内边距 */
            color: #fff;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 0.9rem;
            line-height: 1.2;
            white-space: pre;
            flex: 1;
        }

        .command-terminal .copy-btn {
            position: relative;
            top: auto;
            right: auto;
            transform: none;
            margin: 0 10px;  /* 调整按钮边距 */
            padding: 4px 8px;
            font-size: 0.8rem;
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
            border: none;
            border-radius: 4px;
            opacity: 1;
            height: fit-content;
        }

        .copy-success {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border-radius: 4px;
            animation: fadeInOut 1.5s ease-in-out;
            pointer-events: none;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; }
            20% { opacity: 1; }
            80% { opacity: 1; }
            100% { opacity: 0; }
        }

        #documentationText pre {
            background: #2D2D2D;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 1rem;
            position: relative;
        }

        #documentationText pre code {
            display: block;
            padding: 12px 15px;
            color: #fff;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 0.9rem;
            line-height: 1.2;
            background: transparent;
        }

        #documentationText .command-terminal {
            background: #2D2D2D;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 1rem;
        }

        #documentationText pre {
            position: relative;
            margin: 0;
        }

        #documentationText pre .copy-btn {
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            padding: 4px 8px;
            font-size: 0.8rem;
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
            border: none;
            border-radius: 4px;
            opacity: 0;
            transition: opacity 0.2s;
            cursor: pointer;
        }

        #documentationText pre:hover .copy-btn {
            opacity: 1;
        }

        /* 修改文档代码块中复制按钮的样式 */
        #documentationText .command-terminal pre {
            position: relative;
        }

        #documentationText .command-terminal .copy-btn {
            position: absolute;
            top: 8px;           /* 调整到右上角 */
            right: 8px;
            transform: none;    /* 移除垂直居中变换 */
            margin: 0;
            padding: 4px 8px;
            font-size: 0.8rem;
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
            border: none;
            border-radius: 4px;
            opacity: 0;
            transition: opacity 0.2s;
            cursor: pointer;
            z-index: 10;        /* 确保按钮始终在上层 */
        }

        #documentationText .command-terminal pre:hover .copy-btn {
            opacity: 1;
        }

        /* 调整代码块内边距，避免与复制按钮重叠 */
        #documentationText .command-terminal pre code {
            padding: 12px 15px;
            padding-right: 60px;  /* 为复制按钮留出空间 */
        }

        /* 文档列表样式优化 */
        #documentList {
            border-right: 1px solid var(--border-color);
            padding-right: 2rem;
            min-width: 200px;
        }

        #documentList h2 {
            color: var(--primary-color);
            font-size: 1.2rem;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--border-color);
        }

        #documentList ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        #documentList li {
            margin-bottom: 0.8rem;
        }

        #documentList a {
            color: var(--text-color);
            text-decoration: none;
            display: block;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            transition: all 0.3s ease;
            font-size: 0.95rem;
            border: 1px solid transparent;
        }

        #documentList a:hover {
            background-color: var(--background-color);
            color: var(--primary-color);
            border: 1px solid var(--border-color);
        }

        #documentList a.active {
            background-color: var(--primary-color);
            color: white;
            border: 1px solid var(--primary-color);
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            #documentList {
                border-right: none;
                border-bottom: 1px solid var(--border-color);
                padding-right: 0;
                padding-bottom: 1rem;
                margin-bottom: 1.5rem;
            }

            #documentList ul {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
            }

            #documentList li {
                margin-bottom: 0;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-content">
            <a href="/" class="logo-link">
                <img src="https://cdn.jsdelivr.net/gh/dqzboy/Blog-Image/BlogCourse/docker-proxy.png" alt="Logo" class="logo">
            </a>
            <nav class="nav-menu" id="navMenu">
                <!-- 菜单项将通过 JavaScript 动态加载 -->
            </nav>
        </div>
    </header>

    <div class="container">
        <h1>Docker 镜像加速和镜像搜索</h1>
        
        <div class="tab-container">
            <div class="tab active" onclick="switchTab('accelerate')">镜像加速</div>
            <div class="tab" onclick="switchTab('search')">镜像搜索</div>
            <div class="tab" onclick="switchTab('documentation')">文档教程</div>
        </div>

        <div id="accelerateContent" class="content active">
            <div class="input-group">
                <input type="text" id="imageInput" placeholder="请输入 Docker 镜像名称，例如：nginx 或 mysql:5.7">
                <button onclick="generateCommands(document.getElementById('imageInput').value.trim())">获取加速命令</button>
            </div>
            <div id="result" style="display:none;">
                <h2>加速命令</h2>
                <div id="commandsContainer"></div>
            </div>
            
            <div class="quick-guide">
                <h3>快速使用指南</h3>
                <ol>
                    <li>输入需要拉取的 Docker 镜像名称（例如：nginx, mysql:5.7）</li>
                    <li>点击"获取加速命令"按钮生成加速命令</li>
                    <li>复制并执行命令以加速拉取镜像</li>
                    <li>等待镜像下载完成即可使用</li>
                </ol>
            </div>
            
            <div class="popular-images">
                <h3>热门镜像推荐</h3>
                <div class="image-grid">
                    <div class="image-card" onclick="useImage('nginx')">
                        <h3>Nginx</h3>
                        <div class="description">高性能的HTTP和反向代理服务器</div>
                        <button class="use-image-btn">使用此镜像</button>
                    </div>
                    <div class="image-card" onclick="useImage('mysql')">
                        <h3>MySQL</h3>
                        <div class="description">流行的关系型数据库管理系统</div>
                        <button class="use-image-btn">使用此镜像</button>
                    </div>
                    <div class="image-card" onclick="useImage('redis')">
                        <h3>Redis</h3>
                        <div class="description">开源的内存数据存储系统</div>
                        <button class="use-image-btn">使用此镜像</button>
                    </div>
                    <div class="image-card" onclick="useImage('mongodb')">
                        <h3>MongoDB</h3>
                        <div class="description">流行的 NoSQL 数据库</div>
                        <button class="use-image-btn">使用此镜像</button>
                    </div>
                </div>
            </div>
        </div>

        <div id="searchContent" class="content">
            <div class="search-container">
                <input type="text" id="searchInput" placeholder="请输入 Docker 镜像名称进行搜索">
                <button onclick="searchDockerHub()">搜索Docker镜像</button>
            </div>
            <div class="quick-guide">
                <h3>搜索提示</h3>
                <ul>
                    <li>输入完整的镜像名称可以获得精确结果（例如：nginx, mysql）</li>
                    <li>可以通过关键词搜索相关镜像</li>
                    <li>官方镜像会显示"官方"标记</li>
                    <li>结果会显示镜像的描述和星标数量</li>
                </ul>
            </div>
            <div id="searchResults"></div>
            
            <div class="popular-images">
                <h3>热门搜索</h3>
                <div class="image-grid">
                    <div class="image-card" onclick="document.getElementById('searchInput').value='nginx'; searchDockerHub();">
                        <h3>Web 服务器</h3>
                        <div class="description">包括 Nginx、Apache、Httpd 等Web服务器</div>
                        <button class="use-image-btn">搜索相关</button>
                    </div>
                    <div class="image-card" onclick="document.getElementById('searchInput').value='mysql'; searchDockerHub();">
                        <h3>数据库</h3>
                        <div class="description">MySQL、PostgreSQL、MongoDB 等数据库</div>
                        <button class="use-image-btn">搜索相关</button>
                    </div>
                    <div class="image-card" onclick="document.getElementById('searchInput').value='redis'; searchDockerHub();">
                        <h3>缓存服务</h3>
                        <div class="description">Redis、Memcached 等缓存服务</div>
                        <button class="use-image-btn">搜索相关</button>
                    </div>
                    <div class="image-card" onclick="document.getElementById('searchInput').value='rabbitmq'; searchDockerHub();">
                        <h3>消息队列</h3>
                        <div class="description">RabbitMQ、Kafka 等消息队列服务</div>
                        <button class="use-image-btn">搜索相关</button>
                    </div>
                </div>
            </div>
        </div>

        <div id="documentationContent" class="content">
            <div id="documentList"></div>
            <div id="documentationText"></div>
        </div>
    </div>

    <footer class="footer">
        <p>Copyright © <span id="currentYear"></span> All Rights Reserved. <a href="https://github.com/dqzboy/Docker-Proxy" target="_blank" rel="noopener noreferrer">Docker-Proxy</a></p>
    </footer>

    <button id="backToTopBtn" onclick="scrollToTop()" aria-label="返回顶部">▲</button>

    <script>
        // 设置当前年份
        document.getElementById('currentYear').textContent = new Date().getFullYear();

        document.addEventListener('DOMContentLoaded', (event) => {
            const menuToggle = document.getElementById('menuToggle');
            const navMenu = document.getElementById('navMenu');

            menuToggle.addEventListener('click', () => {
                navMenu.classList.toggle('active');
            });
        });
        
        let proxyDomain = ''; // 默认代理加速地址
        let currentIndex = 0;
        let items = [];

        // 标签切换功能
        function switchTab(tabName) {
            const tabs = document.querySelectorAll('.tab');
            const contents = document.querySelectorAll('.content');

            tabs.forEach(tab => tab.classList.remove('active'));
            contents.forEach(content => content.classList.remove('active'));

            document.querySelector(`.tab:nth-child(${tabName === 'accelerate' ? '1' : (tabName === 'search' ? '2' : '3')}`).classList.add('active');
            document.getElementById(`${tabName}Content`).classList.add('active');

            // 重置显示
            document.getElementById('searchResults').style.display = 'none';
            document.getElementById('result').style.display = 'none';
            document.getElementById('backToTopBtn').style.display = 'none';

            if (tabName === 'documentation') {
                fetchDocumentation();
            } else if (tabName === 'accelerate') {
                // 重置显示状态
                document.querySelector('.quick-guide').style.display = 'block';
                document.querySelector('.popular-images').style.display = 'block';
                document.getElementById('result').style.display = 'none';
                
                const imageInput = document.getElementById('imageInput').value.trim();
                if (imageInput) {
                    generateCommands(imageInput);
                }
            } else if (tabName === 'search') {
                document.getElementById('searchInput').value = '';
            }
        }

        // 生成加速命令
        function generateCommands(imageInput) {
            if (!imageInput) {
                imageInput = document.getElementById('imageInput').value.trim();
            }
            if (!imageInput) {
                alert('请输入 Docker 镜像名称');
                return;
            }
            let [imageName, tag] = imageInput.split(':');
            tag = tag || 'latest';
            
            let originalImage = `${imageName}:${tag}`;
            let proxyImage = '';

            if (!imageName.includes('/')) {
                proxyImage = `${proxyDomain}/library/${imageName}:${tag}`;
            } else {
                proxyImage = `${proxyDomain}/${imageName}:${tag}`;
            }

            const commands = [
                { title: "原始拉取命令", cmd: `docker pull ${originalImage}` },
                { title: "代理拉取镜像", cmd: `docker pull ${proxyImage}` },
                { title: "重命名镜像", cmd: `docker tag ${proxyImage} ${originalImage}` },
                { title: "删除代理镜像", cmd: `docker rmi ${proxyImage}` }
            ];

            const resultDiv = document.getElementById('result');
            const container = document.getElementById('commandsContainer');
            container.innerHTML = '';

            // 将生成的命令添加到结果容器中
            commands.forEach((command, index) => {
                const cmdDiv = document.createElement('div');
                cmdDiv.className = 'step';
                cmdDiv.innerHTML = `
                    <h3>${index + 1}. ${command.title}</h3>
                    <div class="command-terminal">
                        <div class="terminal-header">
                            <div class="terminal-button button-red"></div>
                            <div class="terminal-button button-yellow"></div>
                            <div class="terminal-button button-green"></div>
                        </div>
                        <pre><code>${command.cmd}</code>
                            <button class="copy-btn" onclick="copyToClipboard('${command.cmd}', this)">复制</button>
                        </pre>
                    </div>
                `;
                container.appendChild(cmdDiv);
            });

            // 显示结果并隐藏其他内容
            resultDiv.style.display = 'flex';
            resultDiv.style.flexDirection = 'column';
            document.querySelector('.quick-guide').style.display = 'none';
            document.querySelector('.popular-images').style.display = 'none';
            document.getElementById('backToTopBtn').style.display = 'block';
        }

        // 复制命令到剪贴板
        function copyToClipboard(text, element) {
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(() => {
                    showNotification(element.target || element);
                }, (err) => {
                    console.error('无法复制文本: ', err);
                });
            } else {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showNotification(element.target || element);
            }
        }

        function showNotification(cmdElement) {
            const successDiv = document.createElement('div');
            successDiv.className = 'copy-success';
            successDiv.textContent = '已复制到剪贴板';
            
            // 获取命令所在的 pre 元素
            const preElement = cmdElement.closest('pre');
            preElement.style.position = 'relative';
            preElement.appendChild(successDiv);

            // 1.5秒后移除提示
            setTimeout(() => {
                successDiv.remove();
            }, 1500);
        }

        // 滚动到顶部
        function scrollToTop() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
            // 滚动完成后隐藏按钮
            document.getElementById('backToTopBtn').style.display = 'none';
        }

        // 搜索功能
        async function searchDockerHub() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (!searchTerm) {
                alert('请输入搜索关键词');
                return;
            }

            const searchResults = document.getElementById('searchResults');
            searchResults.innerHTML = '正在搜索...';

            // 显示和隐藏广告逻辑
            searchResults.style.display = 'block';
            document.getElementById('result').style.display = 'none';
            document.getElementById('backToTopBtn').style.display = 'block';

            try {
                const response = await fetch(`/api/search?term=${encodeURIComponent(searchTerm)}`);
                const data = await response.json();

                if (data.results && data.results.length > 0) {
                    const officialImages = data.results.filter(result => result.is_official);
                    const unofficialImages = data.results.filter(result => !result.is_official)
                        .sort((a, b) => (b.star_count || 0) - (a.star_count || 0))
                        .slice(0, 5);

                    searchResults.innerHTML = '';
                    
                    // 显示官方镜像
                    officialImages.forEach(result => {
                        searchResults.appendChild(createResultItem(result, true));
                    });

                    // 显示前5个非官方镜像
                    unofficialImages.forEach(result => {
                        searchResults.appendChild(createResultItem(result, false));
                    });

                    if (officialImages.length === 0 && unofficialImages.length === 0) {
                        searchResults.innerHTML = '未找到匹配的镜像';
                    }
                } else {
                    searchResults.innerHTML = '未找到匹配的镜像';
                }
            } catch (error) {
                console.error('搜索出错:', error);
                searchResults.innerHTML = '搜索时发生错误，请稍后重试';
            }
        }

        function createResultItem(result, isOfficial) {
            const resultItem = document.createElement('div');
            resultItem.className = `search-result-item ${isOfficial ? 'official-image' : ''}`;
            
            const officialBadge = isOfficial ? '<span class="official-badge">官方</span>' : '';
            const stars = result.star_count !== undefined ? `<span class="stars">★ ${result.star_count}</span>` : '';

            resultItem.innerHTML = `
                <h3>${result.name || result.repo_name || '未知名称'} ${officialBadge}</h3>
                <p>描述: ${result.description || result.short_description || '无描述'}</p>
                <p>${stars}</p>
                <button class="use-image-btn" onclick="useImage('${result.name || result.repo_name || ''}')">使用此镜像</button>
            `;
            return resultItem;
        }

        function useImage(imageName) {
            if (imageName) {
                document.getElementById('imageInput').value = imageName;
                switchTab('accelerate');
                // 直接生成加速命令，无需用户再次点击
                generateCommands(imageName);
            } else {
                alert('无效的 Docker 镜像名称');
            }
        }


        async function fetchDocumentation() {
            try {
                const response = await fetch('/api/documentation');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const documents = await response.json();
                console.log('Fetched documents:', documents);

                const documentList = document.getElementById('documentList');
                const documentationText = document.getElementById('documentationText');
                
                if (Array.isArray(documents) && documents.length > 0) {
                    documentList.innerHTML = '<h2>文档列表</h2>';
                    const ul = document.createElement('ul');
                    documents.forEach(doc => {
                        if (doc && doc.id && doc.title) {
                            const li = document.createElement('li');
                            const link = document.createElement('a');
                            link.href = 'javascript:void(0);';
                            link.textContent = doc.title;
                            link.onclick = () => {
                                // 移除其他链接的active类
                                document.querySelectorAll('#documentList a').forEach(a => a.classList.remove('active'));
                                // 添加当前链接的active类
                                link.classList.add('active');
                                showDocument(doc.id);
                            };
                            li.appendChild(link);
                            ul.appendChild(li);
                        }
                    });
                    documentList.appendChild(ul);
                    
                    // 默认选中第一个文档
                    if (documents[0] && documents[0].id) {
                        const firstLink = ul.querySelector('a');
                        if (firstLink) {
                            firstLink.classList.add('active');
                            showDocument(documents[0].id);
                        }
                    }
                } else {
                    documentationText.innerHTML = '暂无文档内容';
                }
            } catch (error) {
                console.error('获取文档列表失败:', error);
                document.getElementById('documentationText').innerHTML = '加载文档列表失败，请稍后再试。错误详情: ' + error.message;
            }
        }

        async function showDocument(id) {
            try {
                console.log('Attempting to show document with id:', id);
                const response = await fetch(`/api/documentation/${id}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const documentData = await response.json();
                console.log('Fetched document:', documentData);

                const documentationText = document.getElementById('documentationText');
                
                if (documentData && documentData.content && documentData.content.trim() !== '') {
                    // 渲染文档内容
                    documentationText.innerHTML = `<h2>${documentData.title || '无标题'}</h2>` + marked.parse(documentData.content);
                    
                    // 为所有代码块添加复制按钮和终端样式
                    const codeBlocks = documentationText.querySelectorAll('pre code');
                    codeBlocks.forEach((codeBlock) => {
                        const pre = codeBlock.parentElement;
                        const code = codeBlock.textContent;
                        
                        // 创建终端风格容器
                        const wrapper = document.createElement('div');
                        wrapper.className = 'command-terminal';
                        wrapper.innerHTML = `
                            <div class="terminal-header">
                                <div class="terminal-button button-red"></div>
                                <div class="terminal-button button-yellow"></div>
                                <div class="terminal-button button-green"></div>
                            </div>
                        `;
                        
                        // 创建复制按钮
                        const copyButton = document.createElement('button');
                        copyButton.className = 'copy-btn';
                        copyButton.textContent = '复制';
                        copyButton.onclick = () => copyToClipboard(code, copyButton);
                        
                        // 正确的DOM操作顺序
                        pre.parentNode.insertBefore(wrapper, pre);  // 1. 先将wrapper插入到pre前面
                        wrapper.appendChild(pre);                   // 2. 将pre移动到wrapper内
                        pre.appendChild(copyButton);               // 3. 将复制按钮添加到pre内
                    });
                } else {
                    documentationText.innerHTML = '该文档没有内容或格式不正确';
                }
            } catch (error) {
                console.error('获取文档内容失败:', error);
                document.getElementById('documentationText').innerHTML = '加载文档内容失败，请稍后再试。错误详情: ' + error.message;
            }
        }

        // 获取并加载配置
        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();

                if (config.logo) {
                    document.querySelector('.logo').src = config.logo;
                }
                if (config.menuItems && Array.isArray(config.menuItems)) {
                    const navMenu = document.getElementById('navMenu');
                    navMenu.innerHTML = ''; // 清空菜单
                    config.menuItems.forEach(item => {
                        const a = document.createElement('a');
                        a.href = item.link;
                        a.textContent = item.text;
                        if (item.newTab) {
                            a.target = '_blank';
                        }
                        navMenu.appendChild(a);
                    });
                }
                if (config.proxyDomain) {
                    proxyDomain = config.proxyDomain;
                }
                // 添加对搜索API的支持
                if (config.searchApiEndpoint) {
                    window.searchApiEndpoint = config.searchApiEndpoint;
                }
            } catch (error) {
                console.error('加载配置失败:', error);
            }
            switchTab('accelerate');
        }

        loadConfig();

        // 添加滚动监听事件
        window.addEventListener('scroll', function() {
            const backToTopBtn = document.getElementById('backToTopBtn');
            if (window.scrollY > 300) {
                backToTopBtn.style.display = 'flex';
            } else {
                backToTopBtn.style.display = 'none';
            }
        });
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/2.0.3/marked.min.js"></script>
</body>
</html>